問題描述
C# / ASP.NET ‑ Web 應用程序鎖定 (C# / ASP.NET ‑ Web Application locking)
我正在開發一個 C#/ASP.NET Web 應用程序,並且在很多情況下我需要進行鎖定。理想情況下,我希望鎖獨立運行,因為它們彼此無關。我一直在考慮 [MethodImpl(MethodImplOptions.Synchronized)]
和一些使用 lock()
的方法,但我有一些問題/疑慮。
看起來 MethodImplOptions.Synchronized 基本上會做
lock(this)`。如果是這種情況,似乎一個線程進入任何同步方法都會阻止所有其他線程進入任何同步方法。那正確嗎?如果是這樣,這還不夠細化。在這一點上,我似乎還不如使用 Application.Lock。(但如果我錯了,請糾正我。)
關於 lock()
,我想弄清楚我應該傳入什麼。我應該創建一組僅用於此目的的對象,並將每個對像用於不同的鎖?有沒有更好的方法?
提前致謝!
參考解法
方法 1:
My preference is to create an object specifically for the lock.
private object lockForSomeResource = new object();
in the class that is managing the contentious resource. Jeff Richter posted an article I read some time ago that recommended this.
You need to think carefully about designing these as a hierarchy if there is any code within a lock that needs another lock. Make sure you always request them in the same order.
方法 2:
I have posted a similar question on this forum, that may help you. Following is the link
Issue writing to single file in Web service in .NET
方法 3:
You can expose some static reference or a singleton, and lock() that.
Maybe you can care to explain why you need such locking and what you will use it for?
方法 4:
Creating discrete object instances at static/application level is the best way for plain exclusive locking.
Should also consider if reader/writer lock instances at application level could also help improve your application concurrency e.g. for reading and updating lists, hashes etc.
(by Matthew Cole、Hamish Smith、pradeeptp、cruizer、stephbu)